package rpc

import (
	"bufio"
	"io"
	"net"
	"net/rpc"
	"reflect"
	"time"

	"github.com/ugorji/go/codec"

	"github.com/go-kit/log"
	"github.com/go-kit/log/level"
)

// 定义一个int 的别名
type Server int

func Start(rpcAddr string, logger log.Logger) error {
	// 创建一个rpc服务
	server := rpc.NewServer()
	// 注册rpc对象
	server.Register(new(Server))
	l, err := net.Listen("tcp", rpcAddr)
	if err != nil {
		level.Error(logger).Log("msg", "listen err", "rpcAddr", rpcAddr, "err", err)
		return err

	}
	level.Info(logger).Log("msg", "start rpc server", "rpcAddr", rpcAddr)
	var mh codec.MsgpackHandle
	mh.MapType = reflect.TypeOf(map[string]interface{}(nil))
	for {
		// 接受一个连接
		conn, err := l.Accept()
		if err != nil {
			level.Error(logger).Log("msg", "accept err", "rpcAddr", rpcAddr, "err", err)
			time.Sleep(100 * time.Millisecond)
			continue
		}
		//用bufio 做缓冲
		var bufConn = struct {
			io.Closer
			*bufio.Reader
			*bufio.Writer
		}{
			conn,
			bufio.NewReader(conn),
			bufio.NewWriter(conn),
		}
		go server.ServeCodec(codec.MsgpackSpecRpc.ServerCodec(bufConn, &mh))

	}

}
